<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :config="table_config" :tableThead="tableThead" :dataList="dataList" :loading="loading"
        @selection-change="selectionChange">
        <template v-slot:status="{ row }">
          <span v-show="row.status == 'CREATE'" class="">创建</span>
          <span v-show="row.status == 'PUT_POND'" class="">已投塘</span>
          <span v-show="row.status == 'SEALED_POND'" class="warningText">已封塘</span>
          <span v-show="row.status == 'COMPLETED'" class="successText">已完成</span>
        </template>
        <template v-slot:supplierBatchCode="{ row }">
          <span :class="row.supplierBatchCode ? '' : 'errText'">{{ row.supplierBatchCode || '未配置供应商' }}</span>
        </template>
        <template v-slot:breedType="{ row }">
          {{ breedTypeObj[row.breedType] }}
        </template>
        <template v-slot:fishPondName="{ row }">
          <span v-show="row.fishPondId">{{ row.fishPondName }}</span>
          <span v-show="!row.fishPondId" class="successText pointer"
            @click="bindFishPond(row, 'bindFishPond')">绑定鱼塘</span>
        </template>
        <template v-slot:unbindFishPond="{ row }">
          <span v-show="row.fishPondId" class="pointer" :class="row.status == 'CREATE' ? 'successText' : 'errText'"
            @click="unbindFishPond(row)">解绑鱼塘</span>
          <span v-show="!row.fishPondId" class="errText">暂未绑定鱼塘</span>
        </template>
        <!-- <template v-slot:info="{ row }">
          <el-button type="text" @click="lookView(row)">查看详情</el-button>
        </template> -->
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'批次'" :breedTypeList="breedTypeList" :fishPondList="fishPondList" @closeDialog="closeDialog"
        :addEditFlag="addEditFlag" :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import TableData from '@/components-production-management/TableData';
import BtnSlot from '@/components-production-management/BtnSlot';
import EnumSlot from '@/components-production-management/EnumSlot';
import AddEdit from './components/addEdit.vue';
//批次
import batchManagement from '@/api/production-management/batch-management.js';
//养殖类型
import breedingTypeManageApi from "@/api/basic-info-manage/breeding-type-manage/index";
//鱼塘
import fishPondApi from "@/api/basic-info-manage/fishPond";
export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit },
  data() {
    return {
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      dialogVisible_lookView: false,
      addEditFlag: 'add',
      selectList: [],
      unitList: [],
      formData: {},
      page: 1,
      total: 10,
      selectIndex: 0,
      searchFormData: {},
      btnList: ['add', 'delete'],
      dataList: [],
      tableThead: [
        // { isShow: true, label: '批次编号', prop: 'batchName' },
        { isShow: true, label: '批次编号', prop: 'batchName', minWidth: '120px' },
        { isShow: true, label: '养殖类型', slotName: 'breedType', minWidth: '120px' },
        { isShow: true, label: '供应商', slotName: 'supplierBatchCode', minWidth: '120px' },
        { isShow: true, label: '养殖状态', slotName: 'status', minWidth: '120px' },
        { isShow: true, label: '关联鱼塘', slotName: 'fishPondName', minWidth: '120px' },
        { isShow: true, label: '解绑鱼塘', slotName: 'unbindFishPond', minWidth: '120px' },
        { isShow: true, label: '创建时间', prop: 'buildDate', minWidth: '140px' },
      ],
      // 配置项
      table_config: {
        isCheckBox: true,

        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '300',
          cols: [
            {
              label: '编辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'danger',
              flag: 'del',
              handleRow: this.handleRow
            },
            {
              label: '完成',
              type: 'warning',
              flag: 'complete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      formItemList: [
        {
          label: '批次编号',
          type: 'input',
          param: 'batchCode',
          defaultSelect: '',
          multiple: false,
          isShow: true
        },
        {
          label: '批次编号',
          type: 'input',
          param: 'batchName',
          defaultSelect: '',
          multiple: false,
          isShow: true
        },
        {
          label: '选择鱼塘',
          type: 'select',
          selectOptions: [],
          param: 'fishPondId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '批次状态',
          type: 'select',
          selectOptions: [
            { text: '创建', value: 'CREATE' },
            { text: '已投塘', value: 'PUT_POND' },
            { text: '已封塘', value: 'SEALED_POND' },
            { text: '已完成', value: 'COMPLETED' },
          ],
          param: 'status',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
      fishPondList: [],
      allfishPondList:[],
      breedTypeList: [],
      breedTypeObj: {}
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    async initData() {
      let { data: breedTypeList } = await breedingTypeManageApi.queryByCondition();
      this.breedTypeList = breedTypeList;
      this.breedTypeObj = breedTypeList.reduce((obj, item) => {
        obj[item.breedTypeNo] = item.breedTypeName;
        return obj;
      }, {});
      let { data: fishPondList } = await fishPondApi.queryByCondition({ bindBatch: false });//bindBatch:false 查询未绑定鱼塘
      let { data: allfishPondList } = await fishPondApi.queryByCondition();//bindBatch:false 查询未绑定鱼塘
      this.fishPondList = fishPondList;
      this.allfishPondList = allfishPondList;
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('fishPondId') !== -1) {
          let selectOptions = this.allfishPondList.map(data => {
            return {
              text: data.pondName, value: data.fishPondId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    delList(deleteList = [], key = 'batchId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await batchManagement.delListById(list);
        if (res.success) {
          this.$message.success(res.message || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.message || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    unbindFishPond(row) {
      this.$confirm('此操作将解绑鱼塘,关联的数据会被清除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await batchManagement.unbindFishPond(row.batchId);
        if (res.success) {
          this.$message.success(res.message || '操作成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.message || '操作失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    // 完成批次
    async completeBatch(id) {
      let { success, message } = await batchManagement.completeBatch({ id });
      if (success) {
        this.$message.success('批次完成')
        this.queryPageByCondition();
        this.initData();
      } else {
        this.$message.warning(message || '操作失败')
      }
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: 10,
        entity: {
          ...this.searchFormData
        }
      }
      this.loading = true;
      batchManagement.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.success == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.message || '分页查询失败')
        }
      }).catch(err => {
        this.loading = false;
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      this.searchFormData = { ...this.searchFormData, ...data };
      for(let key in this.searchFormData){
        if(!this.searchFormData[key]){
          this.searchFormData[key] = null
        }
      }
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    lookView(row) {
      console.log(row)
      this.dialogVisible_lookView = true;
    },
    bindFishPond(row, flag) {
      this.dialogVisible = true;
      this.formData = JSON.parse(JSON.stringify(row))
      this.addEditFlag = flag;
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'del') {
        this.delList([rowData]);
      } else if (item.flag == 'complete') {
        if (rowData.status == 'COMPLETED') {
          this.$message.success('该批次已完成')
          return
        }
        this.completeBatch(rowData.batchId)
      }
      this.addEditFlag = item.flag
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
      this.initData();
    },
  }
};
</script>
<style lang="scss" scoped></style>